package com.controller;


import com.ReturnDTO.ReturnDTO;
import com.entity.User;
import com.service.LoginService;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 登录控制层
 */
@RequestMapping
@Controller
public class UserLoginController {

  @Autowired
  private LoginService loginService;

  /**
   * 内部跳转页面
   * @param modelAndView
   * @return
   */
  @RequestMapping
  public ModelAndView toIndexPage(ModelAndView modelAndView) {
    modelAndView.setViewName("/index");
    return modelAndView;
  }

  @RequestMapping(value = "/toLoginPage")
  public ModelAndView toLoginPage(ModelAndView modelAndView) {
    modelAndView.setViewName("/login");
    return modelAndView;
  }

  /**
   * 登录验证（500，失败,200，成功），设置session
   * @param user
   * @param session
   * @return
   */
  @RequestMapping("/login")
  @ResponseBody
  public ReturnDTO userLion(User user, HttpSession session) {
    if (ObjectUtils.isEmpty(user.getUsername())) {
      return ReturnDTO.getReturnDTO(500, "用戶名不能為空");
    }
    if (ObjectUtils.isEmpty(user.getPassword())) {
      return ReturnDTO.getReturnDTO(500, "密碼不能為空");
    }

    ReturnDTO returnDTO = loginService.userLogin(user);
    if (returnDTO.getCode() == 200) {
      User formUser =  (User)returnDTO.getData();
      session.setAttribute("User", formUser);
      returnDTO.setData("/student/toStudentPage");
    }
    return returnDTO;
  }
}




